package netudp3;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPClient implements Runnable {

	// 发送的目的地址
	private String ip;
	// 端口
	private int port;

	public UDPClient(String ip, int port) {
		super();
		this.ip = ip;
		this.port = port;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		DatagramSocket ds = null;
		BufferedReader br = null;
		try {
			br = new BufferedReader(new InputStreamReader(System.in));
			ds = new DatagramSocket();
			while (true) {
				// 定义一个要发送的内容
				String line = br.readLine();
				byte[] bs = line.getBytes();
				// 创建要发送的IP地址
				InetAddress ia = InetAddress.getByName(ip);
				// 打数据包
				DatagramPacket dp = new DatagramPacket(bs, bs.length, ia, port);
				// 发送
				ds.send(dp);
				System.out.println("我说："+line+"\r\n");
				// 退出
				if ("exit".equals(line)) {
					break;
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println(e.toString());
		} finally {
			if (ds != null) {
				ds.close();
			}
			try {
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
